const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
// check email is valid、check rrequired fields、check input length、check password match
function checkEmail(input) {
    const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (re.test(input.value.trim())) {
        showSuccess(input);
    }
    else {
        showError(input, '邮箱地址无效');
    }
}
function checkRequired(inputArr) {
    inputArr.forEach((input) => {
        if (input.value.trim() === '') {
            showError(input, `${getFieldName(input)}是必填项`);
        }
        else {
            showSuccess(input);
        }
    });
}
function checkLength(input, min, max) {
    if (input.value.trim().length < min) {
        showError(input, `${getFieldName(input)}必须大于${min}个字符`);
    }
    else if (input.value.trim().length > max) {
        showError(input, `${getFieldName(input)}不能大于${max}个字符`);
    }
    else {
        showSuccess(input);
    }
}
function checkPasswordsMatch(input1, input2) {
    if (input1.value.trim() !== input2.value.trim()) {
        showError(input2, '密码不匹配');
    }
}
// get 字段名、Show input error message、show success outline
function getFieldName(input) {
    const formControl = input.parentElement;
    const label = formControl.querySelector('label');
    return label.innerText;
}
function showError(input, message) {
    const formControl = input.parentElement;
    formControl.className = 'form-control error';
    const small = formControl.querySelector('small');
    small.innerText = message;
}
function showSuccess(input) {
    const formControl = input.parentElement;
    formControl.className = 'form-control success';
}
// event listener
document.addEventListener('submit', (e) => {
    e.preventDefault();
    checkRequired([username, email, password, password2]);
    checkLength(username, 3, 15);
    checkLength(password, 6, 25);
    checkEmail(email);
    checkPasswordsMatch(password, password2);
});
